// fileName      :  mysql.go
// createdAt     :  2021-10-10
// description   :

package mysql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	gl "gorm.io/gorm/logger"
	"log"
	"time"
	conf "zl-gin/config"
	"zl-gin/mysql/dblog"
	"zl-gin/mysql/models/migrate"
	"zl-gin/utils"
)

var db *gorm.DB

func InitMysql() {
	log.Println("init mysql...")

	mysqlConf := conf.Get().Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlConf.UserName,
		mysqlConf.Password,
		mysqlConf.Host,
		mysqlConf.Port,
		mysqlConf.DbName,
	)
	// 日志配置
	logConfig := gl.Config{
		SlowThreshold:             1 * time.Second,
		LogLevel:                  utils.Ternary(conf.Get().AppEnv != "prd", gl.Info, gl.Warn).(gl.LogLevel),
		IgnoreRecordNotFoundError: false,
		Colorful:                  false,
	}

	//根据配置文件，SQL语句打印到哪里
	newLogger := NewGormLogger(dblog.GetLogType(), logConfig)
	Cdb, dbErr := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})

	if dbErr != nil {
		log.Panicf("初始化数据库失败, err :%v", dbErr)
	}

	//池化配置
	sqlDB, sqlDBErr := Cdb.DB()
	if sqlDBErr != nil {
		log.Panicf("获取SQLDB失败, err :%v", sqlDBErr)
	}

	sqlDB.SetMaxOpenConns(conf.Get().Gorm.MaxOpenCount)
	sqlDB.SetMaxIdleConns(conf.Get().Gorm.MaxIdleConnection)
	sqlDB.SetConnMaxLifetime(time.Hour)

	if conf.Get().AppEnv != "prd" {
		migrate.AutoMigrate(Cdb)
	}

	db = Cdb
}

func GetDbInstance() *gorm.DB {
	return db
}
